const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const { exec } = require("child_process");
const fileUrl = require("../../tools/fileUrl");
const uploadPath = `${fileUrl.uploadStaticPath}`;
// 设置文件上传目录
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => cb(null, path.extname(file.originalname)),
});
const upload = multer({ storage });

router.post("/", upload.single("file"), (req, res) => {
  const wordFilePath = req.file.path;
  const pdfFilePath = `${uploadPath}/${Date.now()}.pdf`;
  // 使用 LibreOffice 转换 Word 为 PDF
  exec(
    `libreoffice --headless --convert-to pdf ${wordFilePath} --outdir ${path.dirname(
      pdfFilePath
    )}`,
    (error, stdout, stderr) => {
      if (error) {
        console.error(`Error during conversion: ${error.message}`);
        return res.status(500).send("Error during conversion");
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`);
        return res.status(500).send("Error during conversion");
      }

      // 发送 PDF 文件给前端
      const pdfBlob = fs.readFileSync(pdfFilePath);
      res.setHeader("Content-Type", "application/pdf");
      res.setHeader(
        "Content-Disposition",
        `attachment; filename=${path.basename(pdfFilePath)}`
      );
      res.send(pdfBlob);
    }
  );
});

module.exports = router;